package com.example.day12;

import android.annotation.SuppressLint;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.support.v7.widget.DividerItemDecoration;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.TextUtils;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;

import com.google.gson.Gson;
import com.scwang.smartrefresh.layout.SmartRefreshLayout;
import com.scwang.smartrefresh.layout.api.RefreshLayout;
import com.scwang.smartrefresh.layout.listener.OnRefreshListener;
import com.scwang.smartrefresh.layout.listener.OnRefreshLoadMoreListener;

import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.List;

public class HomeFragment extends Fragment {

    String listUrl = "https://www.wanandroid.com/article/list/";
    String bannerUrl = "https://www.wanandroid.com/banner/json";

    int pageIndex = 0;
    private RecyclerView mRecyclerview;

    public static final int BANNER_CODE = 1;
    public static final int LIST_CODE = 2;
    Context context;
    private HomeAdapter homeAdapter;

    @SuppressLint("HandlerLeak")
    Handler handler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);

            switch (msg.what) {

                case BANNER_CODE:
                    BannerBean bannerBean = (BannerBean) msg.obj;

                    List<BannerBean.DataBean> data = bannerBean.getData();

                    homeAdapter.addBannerList(data);
                    break;
                case LIST_CODE:

                    HomeBean homeBean = (HomeBean) msg.obj;
                    List<HomeBean.DataBean.DatasBean> datas = homeBean.getData().getDatas();
                    if (pageIndex == 0) {

//                        结束刷新
                        mSmartlayout.finishRefresh();
                        // 重置数据和刷新
                        homeAdapter.resetDataList(datas);
                    }else{
//                        结束加载更多
                        homeAdapter.loadMore(datas);
                        mSmartlayout.finishLoadMore();
                    }
                    break;
            }
        }
    };

    private static final String TAG = "HomeFragment";
    private SmartRefreshLayout mSmartlayout;

    @Nullable
    @Override
    public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {

        context = getActivity();
        View root = inflater.inflate(R.layout.home_fragment, null);
        initView(root);
        initData();
        return root;
    }

    private void initData() {
        new Thread() {
            @Override
            public void run() {
                super.run();

                String bannerResult = getNetWorkData(bannerUrl);

                String listResult = getNetWorkData(listUrl + pageIndex + "/json");


                Log.d(TAG, "run: " + bannerResult);
                Log.d(TAG, "run: " + listResult);
                // 单独发送banner的数据
                if (!TextUtils.isEmpty(bannerResult)) {
//                    handler 发送消息
                    BannerBean bannerBean = new Gson().fromJson(bannerResult, BannerBean.class);

                    Message message = new Message();
                    message.what = BANNER_CODE;
                    message.obj = bannerBean;
                    handler.sendMessage(message);
                }

//                发送列表的数据
                if (!TextUtils.isEmpty(listResult)) {
//                    handler 发送消息
                    HomeBean homeBean = new Gson().fromJson(listResult, HomeBean.class);


                    Message message = new Message();
                    message.what = LIST_CODE;
                    message.obj = homeBean;
                    handler.sendMessage(message);

                }

            }
        }.start();
    }

    private String getNetWorkData(String requestUrl) {

        try {
            URL url = new URL(requestUrl);
            HttpURLConnection httpURLConnection = (HttpURLConnection) url.openConnection();
            InputStream inputStream = httpURLConnection.getInputStream();
            ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
            byte[] bytes = new byte[1024 * 4];
            int readLength;
            while ((readLength = inputStream.read(bytes)) != -1) {
                outputStream.write(bytes, 0, readLength);
            }

            outputStream.close();
            inputStream.close();
            return outputStream.toString();

        } catch (IOException e) {
            e.printStackTrace();
        }

        return "";
    }

    private void initView(@NonNull final View itemView) {
        mRecyclerview = (RecyclerView) itemView.findViewById(R.id.recyclerview);
        mRecyclerview.setLayoutManager(new LinearLayoutManager(context));
        mSmartlayout = (SmartRefreshLayout) itemView.findViewById(R.id.smartlayout);

        mRecyclerview.addItemDecoration(new DividerItemDecoration(context, DividerItemDecoration.VERTICAL));
        homeAdapter = new HomeAdapter(context);
        mRecyclerview.setAdapter(homeAdapter);

        homeAdapter.setClickItem(new HomeAdapter.ClickItem() {
            @Override
            public void click(HomeBean.DataBean.DatasBean datasBean) {

                Log.d(TAG, "click: " + datasBean.getTitle());

                // 跳转到详情页

                Intent intent = new Intent(context, DetailsActivity.class);
                intent.putExtra("url", datasBean.getLink());
                startActivity(intent);

            }
        });


        mSmartlayout.setOnRefreshLoadMoreListener(new OnRefreshLoadMoreListener() {
            @Override
            public void onLoadMore(@NonNull RefreshLayout refreshLayout) {
//                加载更多

                pageIndex++;
                initData();
            }

            @Override
            public void onRefresh(@NonNull RefreshLayout refreshLayout) {
                // 下拉刷新
                pageIndex = 0;
                initData();
            }
        });

    }


}
